package com.songtech.lottery.controller;

import com.alibaba.fastjson.JSONObject;
import com.songtech.base.core.common.JsonResult;
import com.songtech.lottery.model.SysUser;
import com.songtech.lottery.service.SysUserService;
import com.songtech.lottery.util.WxUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @Author: RenTie
 * @Date: 2019-01-03 11:02
 **/
@RestController
@RequestMapping("/wx")
public class WxController {


    private Logger logger = LoggerFactory.getLogger(WxController.class);

    @Autowired
    private SysUserService sysUserService;

    @PostMapping("/signin")
    public JsonResult signIn(String openId,String accessToken,String name){

//        String openId = map.get("openId");
//        String accessToken = map.get("accessToken");
//        String name = map.get("name");

        try {
            String headImgUrl = "";
            //获取微信用户信息
            JSONObject userJson = WxUtil.getWxUserInfo(accessToken,openId);
            if (userJson != null ) {
                headImgUrl = userJson.getString("headimgurl");
            }
            SysUser sysUser = sysUserService.selectByPrimaryKey(openId);
              if (sysUser == null){
                    //用户信息入缓存和数据库
                    sysUser = new SysUser();
                    sysUser.setUrl(headImgUrl);
                    sysUser.setId(openId);
                    sysUser.setName(name);
                    sysUser.setCreateTime(new Date());
                    sysUser.setIsWin(0);
                    sysUserService.insertSelective(sysUser);
              }else {
                  return JsonResult.fail("已签到！无需重复签到");
              }
        } catch (Exception e) {

        }

        return JsonResult.success();
    }

    @PostMapping("/issign")
    public JsonResult isSignIn(String code){
        String openId = "";
        try {
            JSONObject jsonObject = WxUtil.getWxAccess(code);
            logger.info("微信用户授权信息：",jsonObject);
            if(jsonObject != null) {
                //根据code获得用户openId
                openId = jsonObject.getString("openid");
                SysUser sysUser = sysUserService.selectByPrimaryKey(openId);
                if (sysUser != null) {
                    return JsonResult.success();
                }else {
                    return JsonResult.success(jsonObject);
                }
            }else {
                return JsonResult.fail("微信授权异常");
            }

        } catch (Exception e) {

        }
        return JsonResult.success();
    }

    @GetMapping("/users")
    public JsonResult getWxUser(){
        SysUser user = new SysUser();
        user.setIsWin(0);
        return JsonResult.success(sysUserService.select(user));
    }
}
